﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using NHibernate.Transform;
using Newtonsoft.Json;
using System.Collections;
using ZLCMS.Business.Util;
using ZLCMS.Commands.Pub.Util;
//using ZLCMS.Commands.Pub.Util;

namespace ZLCMS.Web.SystemManage.Basics.Shop.ShippingProduct
{
    public partial class ShippingProductDetail : System.Web.UI.Page
    {
        protected ShopOrderShippingInfo OrderShipping { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            //删除
            if (Request["ajax"] == "1" && !string.IsNullOrEmpty(Request["ids"]))
            {
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    int[] ids = JsonConvert.DeserializeObject<int[]>(Request["ids"]);
                    session.CreateSQLQuery("delete from shop_order_shipping_product where id in (:ids) and OWNER_ACCOUNT=:acc")
                        .SetParameter("acc", UserKit.GetUserAccountFailLogin())
                        .SetParameterList("ids", ids)
                        .ExecuteUpdate();
                }
                Response.End();
                return;
            }
            //确认支付
            if (Request["ajax"] == "1" && !string.IsNullOrEmpty(Request["finish"]))
            {
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    session.CreateSQLQuery("update shop_order_shipping_info set finish_status='1' where id=:id and OWNER_ACCOUNT=:acc")
                          .SetParameter("acc", UserKit.GetUserAccountFailLogin())
                          .SetParameter("id", Int32.Parse(Request["uid"]))
                          .ExecuteUpdate();
                }
                Response.End();
                return;
            }
            if (!IsPostBack)
            {
                //todo 设置页面控件信息

                int uid = 0;
                try
                {
                    uid = Int32.Parse(Request["uid"]);
                }
                catch
                {

                }
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    if (uid > 0)
                    {
                        OrderShipping = session.Get<ShopOrderShippingInfo>(uid);

                    }
                    if (OrderShipping != null)
                    {
                        //保存uid
                        ViewState["uid"] = uid;
                        orderNo.ReadOnly = true;
                    }
                    else
                    {
                        OrderShipping = new ShopOrderShippingInfo();
                        OrderShipping.OrderNo = Request["orderno"];
                        OrderShipping.TotalPrice = 0;
                    }
                    IList<ShopShippingInfo> list = session.CreateCriteria<ShopShippingInfo>().List<ShopShippingInfo>();
                    list.Insert(0, new ShopShippingInfo() { Type = "-1", ShippingName = "--请选择--" });
                    shippinglist.DataSource = list;
                }

                shippinglist.DataTextField = "ShippingName";
                shippinglist.DataValueField = "Type";
                shippinglist.DataBind();
                //在此设置控件的初始属性
                orderNo.Text = OrderShipping.OrderNo;
                shippingno.Text = OrderShipping.ShippingNo;
                price.Text = string.Format("{0}", OrderShipping.TotalPrice);
                shippinglist.SelectedValue = OrderShipping.ShippingType;
                //memo.Text = OrderShipping.

                if (OrderShipping.Id > 0)
                {
                    JGridControl2.Columns.Add(new ListItem() { Text = "序号", Value = "Id" });
                    JGridControl2.Columns.Add(new ListItem() { Text = "商品编号", Value = "ProductNo" });
                    JGridControl2.Columns.Add(new ListItem() { Text = "SKU编号", Value = "SkuProductNo" });
                    JGridControl2.Columns.Add(new ListItem() { Text = "商品名称", Value = "ProductName" });
                    JGridControl2.Columns.Add(new ListItem() { Text = "数量", Value = "Quantity" });
                    JGridControl2.EditorUrl = "/SystemManage/Basics/Shop/ShippingProduct/SetProductDialog.aspx?sid=" + OrderShipping.Id;

                    using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                    {
                        IList<IDictionary> list = session.CreateSQLQuery(@"select ID as Id, SKU_PRODUCT_NO as SkuProductNo,PRODUCT_NO as ProductNo,PRODUCT_NAME as ProductName,
                            QUANTITY as Quantity from shop_order_shipping_product where ORDER_SHIPPING_ID=" + OrderShipping.Id).SetResultTransformer(Transformers.AliasToEntityMap)
                            .List<IDictionary>();
                        foreach (IDictionary item in list)
                        {
                            item["ProductName"] = item["ProductName"] + SkuProductKit.GetSkuItemNames(item["SkuProductNo"] as string, session);
                        }
                        JGridControl2.Value = JsonConvert.SerializeObject(list);
                    }
                }
            }
            else
            {
                //todo 保存数据
                
                int uid = ViewState["uid"] == null ? 0 : (int)ViewState["uid"];

                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    if (uid > 0)
                    {
                        OrderShipping = session.Get<ShopOrderShippingInfo>(uid);
                    }
                    if (OrderShipping == null)
                    {
                        OrderShipping = new ShopOrderShippingInfo();
                        OrderShipping.CreateDate = DateTime.Now;
                        OrderShipping.OrderNo = orderNo.Text;

                        ShopOrderInfo orderInfo = session.CreateQuery("from ShopOrderInfo where OrderNo=:no")
                            .SetParameter("no", orderNo.Text)
                            .UniqueResult<ShopOrderInfo>();
                        if (orderInfo != null)
                        {
                            OrderShipping.OwnerAccount = orderInfo.OwnerAccount;
                            OrderShipping.MemberAccount = orderInfo.MemberAccount;
                            OrderShipping.PayStatus = orderInfo.PayStatus;
                            OrderShipping.ShippingStatus = "0";
                            OrderShipping.FinishStatus = "0";
                        }
                    }

                    //在此设置item的各个属性
                    OrderShipping.OrderNo = orderNo.Text;
                    OrderShipping.ShippingNo = shippingno.Text;
                    OrderShipping.TotalPrice = decimal.Parse(price.Text);
                    OrderShipping.ShippingType = shippinglist.SelectedValue;
                    //保存并更新item
                    session.SaveOrUpdate(OrderShipping);
                    session.Flush();
                }


                //框架返回成功提示
                ZLCMS.Business.DwzFrame.FrameHelper _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);
                ZLCMS.Business.DwzFrame.ReturnCode rc = new ZLCMS.Business.DwzFrame.ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功"
                };

                rc.callbackType = "forward";
                rc.forwardUrl = "/SystemManage/Basics/Shop/ShippingProduct/ShippingProductDetail.aspx?tabid=ShippingProductDetail";
                rc.forwardUrl += "&uid=" + OrderShipping.Id;


                _framePage.Alert(rc);
            }
        }
    }
}